package com.goldenKey.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.goldenKey.common.mapper.AdminMapper;
import com.goldenKey.common.mapper.UserMapper;
import com.goldenKey.admin.pojo.query.AccountQuery;
import com.goldenKey.admin.service.IAccountService;
import com.goldenKey.common.exception.AppException;
import com.goldenKey.common.pojo.enumeration.ExceptionEnum;
import com.goldenKey.common.pojo.po.Admin;
import com.goldenKey.admin.pojo.vo.AccountVo;
import com.goldenKey.common.utils.JasyptEncryptorUtils;
import com.goldenKey.common.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @Author: 吃我一钊
 * @Description: 业务逻辑实现层
 * @Date: 2025/02/02
 */

@Service("adminAccountServeImpl")
public class AccountServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAccountService{

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 管理员登录
     * @param accountQuery
     * @return
     */
    @Override
    public AccountVo login(AccountQuery accountQuery) {
        // 验证账号和密码
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getAccount, accountQuery.getAccount());
        Admin admin = adminMapper.selectOne(queryWrapper);

        if(admin == null) {
            throw new AppException(ExceptionEnum.ACCOUNT_OR_PASSWORD_ERROR);
        }

        // 接着对找到的密码解密
        String plainPassword = JasyptEncryptorUtils.decode(admin.getPassword());
        if(!accountQuery.getPassword().equals(plainPassword)) {  // 密码错误
            throw new AppException(ExceptionEnum.ACCOUNT_OR_PASSWORD_ERROR);
        }

        // 账号验证通过,设置token
        String token = JwtUtils.createToken(String.valueOf(admin.getAdminId()), admin.getAccount());
        AccountVo accountVo = new AccountVo();
        BeanUtils.copyProperties(admin, accountVo);
        accountVo.setAdminToken(token);
        return accountVo;
    }


}